/**
 * @author thienchau
 * @date Apr 21, 2013
 */

package com.cdn.allmobilestore.service;

import static com.cdn.allmobilestore.CommonUtilities.EXTRA_MESSAGE;
import static com.cdn.allmobilestore.CommonUtilities.SENDER_ID;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cdn.allmobilestore.AlertDialogManager;
import com.cdn.allmobilestore.ConnectionDetector;
import com.cdn.allmobilestore.WakeLocker;
import com.cdn.allmobilestore.model.Campaign.CampaignType;
import com.cdn.allmobilestore.object.App;
import com.cdn.allmobilestore.object.AppCollection;
import com.cdn.allmobilestore.object.Category;
import com.cdn.allmobilestore.ulti.AllMobileReference;
import com.cdn.allmobilestore.ulti.Constant;
import com.cdn.allmobilestore.ulti.GlobalApplication;
import com.cdn.allmobilestore.ulti.Ulti;
import com.google.android.gcm.GCMRegistrar;
import com.google.gson.JsonArray;

public class AllMobileStoreWebService extends BaseService {

	public static void registerDevice(final Context activity) {
		
		Log.i(Constant.TAG_WEBSERVICE, "registerDevice: ");
		// Asyntask
		final AsyncTask<Void, Void, Void> mRegisterTask;

		// Alert dialog manager
		AlertDialogManager alert = new AlertDialogManager();

		// Connection detector
		ConnectionDetector cd;

		cd = new ConnectionDetector(activity);

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(activity, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}

		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(activity);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(activity);

		//
		// activity.registerReceiver(mHandleMessageReceiver, new IntentFilter(
		// DISPLAY_MESSAGE_ACTION));

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(activity);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			GCMRegistrar.register(activity, SENDER_ID);
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(activity)) {
				// Skips registration.
				Toast.makeText(activity, "Already registered with GCM",
						Toast.LENGTH_LONG).show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				// final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						registerToServer(activity, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						// mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
	}

	private static final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			// Waking up mobile if it is sleeping
			// WakeLocker.acquire(getApplicationContext());

			/**
			 * Take appropriate action on this message depending upon your app
			 * requirement For now i am just displaying it on the screen
			 * */

			// Showing received message
			// lblMessage.append(newMessage + "\n");
			

			// Releasing wake lock
			WakeLocker.release();
		}
	};

	private static int registerToServer(Context activity, String regID) {
		String imei = Ulti.getImei(activity);
		String phoneName = Ulti.getDeviceName();

		if (!Ulti.isNetworkAvailable(activity)) {
			return Constant.ERROR_NETWORK;
		}

		String url = String.format(Constant.REGISTER_GCM_URL, regID, imei,
				phoneName);
		url = url.replaceAll(" ", "%20");
		Log.i(Constant.TAG_WEBSERVICE, "url: " + url);

		final String result = downLoadUrlInBuffer(url,
				Constant.TIME_FOR_TIME_OUT);
		Log.i(Constant.TAG_WEBSERVICE, "result: " + result);
		try {
			if (!TextUtils.isEmpty(result)) {
				AllMobileReference.saveRegisterGCMState(activity);
				return Constant.KEY_SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Constant.ERROR_REQUEST;
	}


	public static int checkVersion(Context context, StringBuilder resultVersion) {
		Log.i(Constant.TAG_WEBSERVICE,"checkVersion");
		if (!Ulti.isNetworkAvailable(context)) {
			return Constant.ERROR_NETWORK;
		}
		String version = "";
		PackageInfo pInfo;
		try {
			pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			version = pInfo.versionName;
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		
		String url = String.format(Constant.CHECK_VERSION_URL, version);
		Log.i(Constant.TAG_WEBSERVICE, "url: " + url);

		
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(Constant.CHECK_VERSION_URL);
	    String result ="";
	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("version", version));
	        nameValuePairs.add(new BasicNameValuePair("imei", Ulti.getImei(context)));
	        nameValuePairs.add(new BasicNameValuePair("email",Ulti.getUsername()));
	        nameValuePairs.add(new BasicNameValuePair("device",Ulti.getDeviceName()));
	         
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response 	= httpclient.execute(httppost);
	        InputStream is 			= response.getEntity().getContent();
	         result 			= Ulti.inputStreamToString(is);
	       
	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
		
		
		
		try {
			
			if(result != null){
				JSONObject jobj = new JSONObject(result);
				String adv_type = "";
				String adv_promotion_url = "";
				String adv_campaign_url = "";
				String adv_login = "";
				String checkResult = jobj.getString("checkversion");
				Log.i(Constant.TAG_WEBSERVICE, "checkResult: " + checkResult);
				if(jobj.has("adv")){
					String adv 			= jobj.getString("adv");
					if(adv != null){
						JSONObject advObj	= new JSONObject(adv);
						
						adv_type			= advObj.getString("adv_type");
						adv_login			= advObj.getString("adv_login");
						adv_promotion_url  	= advObj.getString("adv_promotion_url");
						adv_campaign_url 	= advObj.getString("adv_campaign_url");
						if(adv_login.equals("1")){
							GlobalApplication._().getmCampaign().setRequireLogin(true);
						}
						else{
							GlobalApplication._().getmCampaign().setRequireLogin(false);
						}
						if(adv_type.equals("campaign")){
							GlobalApplication._().getmCampaign().setmType(CampaignType.CAMPAIGN);
						}
						else{
							GlobalApplication._().getmCampaign().setmType(CampaignType.APPDETAIL);
						}
						GlobalApplication._().getmCampaign().setHasCampaign(true);
						GlobalApplication._().getmCampaign().setmCampaignPromoUrl(adv_promotion_url);
						GlobalApplication._().getmCampaign().setmCampaignUrl(adv_campaign_url);
					}					
				}
	 
				if(!checkResult.isEmpty()){
					resultVersion.append(checkResult);
					return Constant.KEY_SUCCESS;
				}
							
			}
						
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Constant.ERROR_REQUEST;
	}
}
